<template>
  <div class="community-list-container">
    <el-card class="community-card">
      <template #header>
        <div class="card-header">
          <span>小区管理</span>
          <div class="header-buttons">
            <el-button 
              type="success" 
              @click="handleTemplateImport"
            >
              <el-icon><Upload /></el-icon>
              模板导入
            </el-button>
            <el-button 
              type="primary" 
              @click="handleAdd"
            >
              <el-icon><Plus /></el-icon>
              新增小区
            </el-button>
          </div>
        </div>
      </template>
      
      <!-- 搜索区域 -->
      <div class="search-area">
        <el-form :model="searchForm" inline>
          <el-form-item label="小区名称">
            <el-input
              v-model="searchForm.communityName"
              placeholder="请输入小区名称"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="所属区域">
            <el-tree-select
              v-model="searchForm.regionId"
              :data="regionTreeData"
              :props="treeProps"
              placeholder="请选择区域"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px">
              <el-option :label="STATUS.ENABLED" :value="1" />
              <el-option :label="STATUS.DISABLED" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 表格区域 -->
      <div class="table-area">
        <!-- 空状态显示 -->
        <div v-if="showEmptyState" class="empty-state">
          <el-empty 
            :description="emptyStateMessage"
            :image-size="120"
          >
            <template #description>
              <p class="empty-description">{{ emptyStateDescription }}</p>
            </template>
            <template #extra>
              <el-button 
                type="primary" 
                @click="handleAdd"
              >
                <el-icon><Plus /></el-icon>
                新增小区
              </el-button>
            </template>
          </el-empty>
        </div>
        
        <!-- 数据表格 -->
        <el-table
          v-else
          v-loading="loading"
          :data="tableData"
          border
          stripe
          style="width: 100%"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="communityName" label="小区名称" min-width="150" />
          <el-table-column prop="regionName" label="所属区域" min-width="120" />
          <el-table-column prop="address" label="地址" min-width="200" show-overflow-tooltip />
          <el-table-column prop="propertyCompanyName" label="物业公司" min-width="150" show-overflow-tooltip>
            <template #default="{ row }">
              <span v-if="row.propertyCompanyName">{{ row.propertyCompanyName }}</span>
              <span v-else class="no-property-company">-</span>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="80" align="center">
            <template #default="{ row }">
              <el-tag :type="row.status === 1 ? 'success' : 'danger'">
                {{ row.status === 1 ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180" />
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button 
                type="primary" 
                size="small" 
                text 
                @click="handleEdit(row)"
              >
                编辑
              </el-button>
              <el-button 
                type="success" 
                size="small" 
                text 
                @click="handleZoneManagement(row)"
              >
                分区
              </el-button>
              <el-button 
                type="danger" 
                size="small" 
                text 
                @click="handleDelete(row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div v-if="!showEmptyState" class="pagination-area">
          <el-pagination
            v-model:current-page="pagination.current"
            v-model:page-size="pagination.size"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>
    
    <!-- 小区表单弹窗 -->
    <CommunityForm 
      v-model:visible="formVisible"
      :form-data="currentCommunity"
      @success="handleFormSuccess"
    />


  </div>
</template>

<script setup lang="ts">
/**
 * 小区管理页面
 * @author Wu.Liang
 * @date 2024-12-21
 */
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh, Setting, Message, Upload } from '@element-plus/icons-vue'
import { useRegionStore } from '@/store/region'
import { useUserStore } from '@/store/user'
import { communityApi } from '@/api/community'
import { hasPermission } from '@/utils/permission'
import { showSuccess, showError, showWarning, showInfo, showLoadError, showDeleteError } from '@/utils/message'
import { STATUS } from '@/constants'
import CommunityForm from './CommunityForm.vue'


// 状态管理
const regionStore = useRegionStore()
const userStore = useUserStore()
const router = useRouter()

// 响应式数据
const loading = ref(false)
const tableData = ref<any[]>([])
const formVisible = ref(false)
const currentCommunity = ref<any>(null)

// 搜索表单
const searchForm = reactive({
  communityName: '',
  regionId: undefined as number | undefined,
  status: undefined as number | undefined
})

// 分页数据
const pagination = reactive({
  current: 1,
  size: 20,
  total: 0
})

// 树形组件配置
const treeProps = {
  children: 'children',
  label: 'regionName',
  value: 'id'
}

// 计算属性
const regionTreeData = computed(() => regionStore.regionTreeData)

// 权限判断computed
const isSuperAdmin = computed(() => {
  return userPermissionInfo.value.isSuperAdmin
})

const hasPropertyCompany = computed(() => {
  return userPermissionInfo.value.hasPropertyCompany
})

const canManage = computed(() => {
  return isSuperAdmin.value || hasPropertyCompany.value
})

const canDelete = computed(() => {
  return isSuperAdmin.value || hasPropertyCompany.value
})

// 初始化权限信息，防止未定义报错
const userPermissionInfo = ref({
  isSuperAdmin: false,
  hasPropertyCompany: false,
  propertyCompanyId: null as number | null,
  propertyCompanyName: ''
})

// 加载用户权限信息
const loadUserPermissionInfo = async () => {
  try {
    // 首先确保公司信息是最新的
    await userStore.checkAndUpdateCompanyInfo()
    
    const permission = await userStore.getUserDataScope()
    // 整体对象赋值，避免响应式丢失
    userPermissionInfo.value = {
      isSuperAdmin: permission.isSuperAdmin,
      hasPropertyCompany: permission.hasPropertyCompany,
      propertyCompanyId: permission.companyId,
      propertyCompanyName: permission.companyName
    }
    console.log('权限信息加载完成:', userPermissionInfo.value)
  } catch (error) {
    console.error('加载权限信息失败:', error)
    userPermissionInfo.value = {
      isSuperAdmin: false,
      hasPropertyCompany: false,
      propertyCompanyId: null,
      propertyCompanyName: ''
    }
  }
}

// 检查用户是否有删除权限
const hasDeletePermission = (row: any) => {
  // 超级管理员拥有所有删除权限
  if (isSuperAdmin.value) {
    return true
  }
  
  // 物业公司用户只能删除本公司关联的小区
  if (hasPropertyCompany.value) {
    // 如果小区有关联的物业公司信息，检查是否匹配
    if (row.propertyCompanyId) {
      return row.propertyCompanyId === userStore.userInfo?.propertyCompanyId
    }
    // 如果没有物业公司信息，默认允许删除（后端会进行权限校验）
    return true
  }
  
  // 普通用户无删除权限
  return false
}

// 权限提示信息
const permissionTipTitle = computed(() => {
  if (isSuperAdmin.value) {
    return '超级管理员权限'
  } else if (hasPropertyCompany.value) {
    return '物业公司用户权限'
  } else {
    return '普通用户权限'
  }
})

const permissionTipDescription = computed(() => {
  if (isSuperAdmin.value) {
    return '您拥有所有小区的管理权限，可以查看和管理所有小区数据。'
  } else if (hasPropertyCompany.value) {
    return `您只能查看和管理关联物业公司的小区数据。新增的小区将自动关联到您的物业公司。`
  } else {
    return '您只能查看小区数据，无法进行任何操作。如需操作权限，请联系管理员。'
  }
})

const permissionTipType = computed(() => {
  if (isSuperAdmin.value) {
    return 'success'
  } else if (hasPropertyCompany.value) {
    return 'info'
  } else {
    return 'warning'
  }
})

// 空状态相关计算属性
const showEmptyState = computed(() => {
  return !isSuperAdmin.value && (!tableData.value || tableData.value.length === 0)
})

const emptyStateMessage = computed(() => {
  if (isSuperAdmin.value) {
    return '暂无小区数据'
  } else if (hasPropertyCompany.value) {
    return '暂无关联的小区数据'
  } else {
    return '暂无权限访问小区数据'
  }
})

const emptyStateDescription = computed(() => {
  if (isSuperAdmin.value) {
    return '当前没有小区数据，您可以点击下方按钮新增小区'
  } else if (hasPropertyCompany.value) {
    return '当前没有关联的小区数据，您可以点击下方按钮新增小区'
  } else {
    return '请联系管理员分配相关小区权限'
  }
})

// 权限提示相关计算属性
const showPermissionTip = computed(() => {
  // 非超级管理员显示权限提示
  return !isSuperAdmin.value
})

const userDataScopeInfo = computed(() => {
  // 兜底：如userInfo或dataScope不存在，返回['ALL']
  const dataScope = (userStore.userInfo && Array.isArray((userStore.userInfo as any).dataScope))
    ? (userStore.userInfo as any).dataScope as string[]
    : ['ALL']
  if (dataScope.includes('ALL')) {
    return '全部数据'
  } else if (dataScope.includes('NONE')) {
    return '无数据权限'
  } else {
    return dataScope.join(', ')
  }
})

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadData()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    communityName: '',
    regionId: undefined,
    status: undefined
  })
  handleSearch()
}

// 加载数据
const loadData = async () => {
  try {
    loading.value = true
    const params: any = {
      current: pagination.current,
      size: pagination.size
    }
    
    // 只添加有值的搜索条件
    if (searchForm.communityName) {
      params.communityName = searchForm.communityName
    }
    if (searchForm.regionId !== undefined) {
      params.regionId = searchForm.regionId
    }
    if (searchForm.status !== undefined) {
      params.status = searchForm.status
    }
    
    const response = await communityApi.getCommunityPage(params)
    
    // 获取原始数据
    let rawData = response.data.records || []
    let totalCount = response.data.total || 0
    
    // 超级管理员显示所有数据，不需要前端过滤
    if (isSuperAdmin.value) {
      tableData.value = rawData
      pagination.total = totalCount
      console.log('超级管理员显示所有数据:', rawData.length, '条')
    } else {
      // 非超级管理员，后端已经进行了数据权限过滤，直接显示返回的数据
      tableData.value = rawData
      pagination.total = totalCount
      console.log('非超级管理员显示过滤后数据:', rawData.length, '条')
      
      // 如果数据为空，显示提示信息
      if (rawData.length === 0) {
        showWarning('暂无小区数据')
      }
    }
  } catch (error) {
    console.error('加载小区列表失败:', error)
    showError('加载小区列表失败')
  } finally {
    loading.value = false
  }
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.current = 1
  loadData()
}

// 当前页变化
const handleCurrentChange = (current: number) => {
  pagination.current = current
  loadData()
}

// 新增小区
const handleAdd = () => {
  currentCommunity.value = null
  formVisible.value = true
}

// 模板导入
const handleTemplateImport = () => {
  router.push('/region/community/template-import')
}

// 编辑小区
const handleEdit = async (row: any) => {
  try {
    // 先获取完整的小区详情数据
    const response = await communityApi.getCommunityDetail(row.id)
    if (response.data) {
      currentCommunity.value = response.data
    } else {
      // 如果获取详情失败，使用列表数据
      currentCommunity.value = { ...row }
    }
    formVisible.value = true
  } catch (error) {
    console.error('获取小区详情失败:', error)
    // 获取详情失败时，使用列表数据
    currentCommunity.value = { ...row }
    formVisible.value = true
  }
}

// 分区管理
const handleZoneManagement = (row: any) => {
  // 跳转到分区管理页面，并传递小区信息
  router.push({
    path: '/region/zone-management',
    query: {
      communityId: row.id,
      communityName: row.communityName,
      propertyCompanyId: row.propertyCompanyId
    }
  })
}



// 删除小区
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除小区"${row.communityName}"吗？删除后不可恢复！`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await communityApi.deleteCommunity(row.id)
    showSuccess('删除成功')
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      showError('删除失败')
    }
  }
}



// 联系管理员
const handleContactAdmin = () => {
  showInfo('请联系系统管理员分配相关小区权限')
}

// 表单提交成功
const handleFormSuccess = () => {
  formVisible.value = false
  showSuccess('操作成功')
  loadData()
}

// 初始化数据
const initData = async () => {
  try {
    console.log('开始初始化小区管理页面数据...')
    
    // 1. 首先加载用户权限信息
    await loadUserPermissionInfo()
    
    // 2. 等待权限信息完全加载
    await new Promise(resolve => setTimeout(resolve, 100))
    
    // 3. 加载区域树数据
    await regionStore.getRegionTree()
    
    // 4. 最后加载小区列表数据
    await loadData()
    
    console.log('小区管理页面数据初始化完成')
    console.log('最终权限状态:', {
      isSuperAdmin: isSuperAdmin.value,
      hasPropertyCompany: hasPropertyCompany.value,
      hasAddPermission: isSuperAdmin.value || hasPropertyCompany.value
    })
  } catch (error) {
    console.error('初始化数据失败:', error)
    showError('初始化数据失败')
  }
}

// 组件挂载时初始化
onMounted(async () => {
  try {
    console.log('开始初始化小区管理页面...')
    
    // 1. 先加载权限信息，确保首次渲染时权限已就绪
    await loadUserPermissionInfo()
    
    // 2. 权限加载完成后，再加载业务数据
    await regionStore.getRegionTree()
    await loadData()
    
    console.log('小区管理页面初始化完成')
    console.log('最终权限状态:', userPermissionInfo.value)
  } catch (error) {
    console.error('页面初始化失败:', error)
    showError('页面初始化失败')
  }
})


</script>

<style lang="scss" scoped>
.community-list-container {
  padding: 20px;
  
  .community-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .header-buttons {
        display: flex;
        gap: 10px;
      }
    }
    
    .search-area {
      margin-bottom: 20px;
      padding: 20px;
      background-color: #f5f7fa;
      border-radius: 4px;
    }
    
    .permission-tip {
      margin-bottom: 16px;
      
      .permission-tip-content {
        p {
          margin: 8px 0;
          color: #606266;
          font-size: 14px;
          line-height: 1.5;
        }
        
        .data-scope-info {
          margin-top: 8px;
          
          .el-tag {
            margin-right: 8px;
          }
        }
      }
    }
    
    .table-area {
      .empty-state {
        display: flex;
        justify-content: center;
        align-items: center;
        min-height: 400px;
        padding: 40px 20px;
        
        .empty-description {
          margin: 10px 0;
          color: #909399;
          font-size: 14px;
        }
      }
      
      .pagination-area {
        margin-top: 20px;
        text-align: right;
      }
    }
  }
}

// 物业公司样式
.no-property-company {
  color: #c0c4cc;
  font-style: italic;
}
</style> 